import os
import csv
import logging
import portalocker
from pathlib import Path

logger = logging.getLogger(__name__)

def setup_logger(log_file="", level=logging.INFO):
    logger = logging.getLogger()
    logger.setLevel(level)

    if not logger.handlers:
        formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')

        # 控制台输出
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(formatter)
        logger.addHandler(console)

        # 文件输出
        if (log_file):
            Path(log_file).parent.mkdir(parents=True, exist_ok=True)
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(logging.INFO)
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)    
    return logger

def get_logger(name):
    logger = logging.getLogger(name)
    
    # 添加一些辅助方法
    def log_error_with_exc(msg, *args, **kwargs):
        """记录错误并自动包含异常堆栈"""
        kwargs['exc_info'] = True
        logger.error(msg, *args, **kwargs)
    
    # 添加到日志记录器
    logger.error_exc = log_error_with_exc
    
    return logger

def csv_read_list(path):
    data = []
    if not os.path.exists(path):
        return data
    with portalocker.Lock(path, 'r', encoding="utf-8") as f:
        reader = csv.reader(f)
        for row in reader:
            data.append(row)
    return data

def csv_read_multi_list(paths):
    data = []
    for path in paths:
        data += csv_read_list(path)
    return data

def csv_write_list(path, user_data, mode):
    with portalocker.Lock(path, mode, encoding="utf-8", newline = "") as f:
        csv_write = csv.writer(f)
        csv_write.writerows(user_data)

if __name__ == '__main__':
    setup_logger()
    logger.warning("test")
